package com.atguigu.gmall.cart.controller;

import com.atguigu.gmall.cart.service.CartInfoService;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.security.krb5.internal.AuthContext;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author BrookPeng
 * @Date 2020/12/4 11:02
 * @Version 1.0
 *
 *  购物车管理
 *   查询购物车
 *   加入购物车
 *   去购物车结算
 *   + -
 *   删除
 *   清空购物车
 *   选中购物车中的商品
 *
 *    Swagger
 *     /admin/** 后台
 *     /api/** 前台
 */
@RestController
@RequestMapping("/api/cart")
public class CartApiController {

    @Autowired
    private CartInfoService cartInfoService;

    // 加入购物车 临时用户/登陆用户
    @GetMapping("/addCart/{skuId}/{skuNum}")
    public CartInfo addCart(
            @PathVariable("skuId") Long skuId,
            @PathVariable("skuNum") Integer skuNum,
            HttpServletRequest request
    ) {
        String userId = AuthContextHolder.getUserId(request);
        if (StringUtils.isEmpty(userId)) {
            userId = AuthContextHolder.getUserTempId(request);
        }
        // 加入购物车 并返回最新购物车 页面回显
        CartInfo cartInfo = cartInfoService.addCart(skuId, skuNum, userId);
        return cartInfo;
    }

    // 查询购物车列表集合
    @GetMapping("/cartList")
    public Result cartList(HttpServletRequest request) {

        // 登陆用户ID
        String userId = AuthContextHolder.getUserId(request);
        // 临时用户ID
        String userTempId = AuthContextHolder.getUserTempId(request);
        List<CartInfo> cartInfos = cartInfoService.cartList(userTempId, userId);
        return Result.ok(cartInfos);
    }

    // 更新选中或者取消购物车商品的状态
    @GetMapping("/checkCart/{skuId}/{isChecked}")
    public Result checkCart(@PathVariable(value = "skuId") Long skuId,
                            @PathVariable(value = "isChecked") Integer isChecked,
                            HttpServletRequest request) {

        String userId = AuthContextHolder.getUserId(request);
        String userTempId = AuthContextHolder.getUserTempId(request);
        if (StringUtils.isEmpty(userId)) {
            userId = userTempId;
        }
        cartInfoService.checkCart(skuId, isChecked, userId);

        return Result.ok();
    }

    // 商品清单
    @GetMapping("/getCartCheckedList")
    public List<CartInfo> getCartCheckedList(HttpServletRequest request) {

        String userId = AuthContextHolder.getUserId(request);
        return cartInfoService.getCartCheckedList(userId);
    }
}